// useWebSocket.js
const { ref, onMounted, onBeforeUnmount } = Vue;

class WebSocketService {
    constructor(url) {
        this.socket = null;
        this.url = url;
        this.callbacks = {};
        this.expectConnent = true; //期望连接
        this.heartbeat = 0;
        this.active = false;
    }

    // 连接WebSocket
    connect() {
        this.socket = new WebSocket(this.url);
        this.socket.onopen = () => {
            console.log('WebSocket连接已建立');

            if (this.callbacks['open']) {
                this.callbacks['open']();
            }
            this.active = true;
            //心跳
            clearInterval(this.heartbeat);
            this.heartbeat = setInterval(()=>{
                if(this.active){
                    this.active = false;
                    this.send({command:"ping"});
                }else if(this.expectConnent){
                    this.socket.close();
                    this.socket = null;
                    this.connect();
                }
            },10000)
        };


        this.socket.onmessage = (event) => {
            const data = JSON.parse(event.data);
            console.log('收到消息:', data);
            if(data.playload === 'pong'){
                this.active = true;
                return;
            }
            if (this.callbacks['message']) {
                this.callbacks['message'](data);
            }
        };

        this.socket.onclose = () => {
            console.log('WebSocket连接已关闭');
            if (this.callbacks['close']) {
                this.callbacks['close']();
            }
            if(this.expectConnent){
                setTimeout(()=>{this.connect()},3000)
            }
        };

        this.socket.onerror = (error) => {
            console.error('WebSocket发生错误:', error);
            if (this.callbacks['error']) {
                this.callbacks['error'](error);
            }
        };
    }

    // 发送消息
    send(message) {
        if (this.socket && this.socket.readyState === WebSocket.OPEN) {
            this.socket.send(JSON.stringify(message));
        } else {
            console.error('WebSocket未连接，无法发送消息');
        }
    }

    // 注册回调函数
    on(event, callback) {
        this.callbacks[event] = callback;
    }

    // 关闭WebSocket连接
    close() {
        this.expectConnent =false;
        if (this.socket) {
            this.socket.close();
        }
    }
}


module.exports =(url)=>{
    const ws = new WebSocketService(url);
    onBeforeUnmount(() => {
        ws.close();
    });
    return ws;
}